//
//  NSArray+JKExtension.m
//  Category
//
//  Created by jamalping on 16/4/6.
//  Copyright © 2016年 jamalping. All rights reserved.
//

#import "NSArray+JKExtension.h"

@implementation NSArray (JKExtension)

// 基本排序
- (NSArray *)sort
{
    return [self sortedArrayUsingSelector:@selector(compare:)];
}

// 根据数组中对象的某个属性进行排序
- (NSArray *)sortObjectWithKey:(NSString *)key ascend:(BOOL)ascend {
    NSSortDescriptor *dortDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:ascend];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&dortDescriptor count:1];
    return [self sortedArrayUsingDescriptors:sortDescriptors];
}

// 将数组变成字符串(格式化数组并在数组每个元素之间插入一个字符串)
- (NSString *)getNumberStringByFormat:(NSString*)format
                       joinedByString:(NSString *)joinString {
    int count = (int)[self count];
    NSMutableString *mStr = [NSMutableString stringWithCapacity:count];
    for (int i = 0; i < count; i ++) {
        if (i==count-1) {
            NSString *_format = [NSString stringWithFormat:@"%@",format];
            [mStr appendFormat:_format,[[self objectAtIndex:i] intValue]];
        }else{
            NSString *_format = [NSString stringWithFormat:@"%@%@",format,joinString];
            [mStr appendFormat:_format,[[self objectAtIndex:i] intValue]];
        }
    }
    return mStr;
}

- (void)each:(void (^)(id))block
{
    for (id obj in self) {
        block(obj);
    }
}

- (NSArray *)filter:(BOOL (^)(id))block
{
    NSMutableArray *rslt = [NSMutableArray array];
    for (id obj in self) {
        if (block(obj)) {
            [rslt addObject:obj];
        }
    }
    return rslt;
}

- (NSArray *)map:(id (^)(id))block
{
    NSMutableArray *rslt = [NSMutableArray array];
    for (id obj in self) {
        if (block(obj)) {
            [rslt addObject:block(obj)];
        }
    }
    return rslt;
}

- (id)reduce:(id)initial withBlock:(id (^)(id,id))block
{
    id rslt = initial;
    for (id obj in self) {
        rslt = block(rslt, obj);
    }
    return rslt;
    
}

@end
